<template>
    <div>
        <el-row>
            <el-col :span="7">
                <div class="bg-left" >
                    <el-form :model="dataForm" @keyup.enter.native="getDataList()">
                        <el-form-item label="查找设备">
                            <el-select v-model="dataForm.deviceType" clearable placeholder="请选择" style="width:67%" filterable clearable>
                                <el-option v-for="item in options1" :key="item.id" :label="item.deviceType"
                                    :value="item.deviceType"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="查询时间" style="margin-top:0.9vh">
                            <el-date-picker v-model="dataForm.startTime" popper-class="eventTime"
                                value-format="yyyy-MM-dd HH:mm" format="yyyy-MM-dd HH:mm" type="datetime"
                                :picker-options="pickerOptions0" placeholder="开始时间" style="width:67%"
                                @change="startTimeChange"></el-date-picker>
                            <div style="margin-top:0.9vh">
                                <span class="queryText">至</span>
                                <el-date-picker v-model="dataForm.endTime" popper-class="eventTime"
                                    value-format="yyyy-MM-dd HH:mm" format="yyyy-MM-dd HH:mm" type="datetime"
                                    :picker-options="pickerOptions1" placeholder="结束时间" style="width:67%"
                                    @change="endTimeChange"></el-date-picker>
                            </div>
                        </el-form-item>
                        <el-form-item label="故障等级" style="margin-top:0.9vh">
                            <el-select v-model="dataForm.grade" clearable placeholder="请选择" style="width:67% ">
                                <el-option v-for="item in options" :key="item.value" :label="item.label"
                                    :value="item.value"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="门号" style="margin-left:28px" >
                            <el-select v-model="dataForm.doorNo" clearable placeholder="请选择" style="width:71.5% ">
                                <el-option v-for="item in doorNoList" :key="item.id" :label="item.doorNo"
                                    :value="item.doorNo"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item style="margin-top:0.9vh">
                            <el-button type="primary" style="margin-left:3.6vw" @click="getDataList()">搜索</el-button>
                            <el-button type="info" style="margin-left:1.5vw" @click="resetForm()">重置</el-button>
							<!-- <el-button type="info" v-loading.fullscreen.lock="fullscreenLoading" @click="exportHandleNew()">{{ $t('export') }}</el-button> -->
                        </el-form-item>
                    </el-form>
                </div>
            </el-col>
            <el-col :span="8">
                <div class="bg-center">
                    <div class="chartTitleText">报警数量区域统计</div>
                    <div class="chartBox" id="chart1"></div>
                </div>
            </el-col>
            <el-col :span="9">
                <div class="bg-right">
                    <div class="chartTitleText">报警类型统计</div>
                    <div class="chartBox" id="chart2"></div>
                </div>
            </el-col>
        </el-row>
        <el-row>
            <el-button type="primary" style="margin-top: 10px;" @click="downLoadAll()">合并导出</el-button>
        </el-row>
        <el-row class="bg-bottom">
            <el-col :span="24" class="titleContent">
                <span class="titleText">信息列表</span>
                <div class="print" @click="printTable()">
                    <img src="../../../assets/img/dayinji.png" alt="">
                    <span>打印</span>
                </div>
            </el-col>
            <el-table ref="multipleTable" v-loading="dataListLoading" :data="dataList" border style="width: 100%;">
                <el-table-column type="selection" header-align="center" align="center"></el-table-column>
                <el-table-column prop="grade" label="故障等级" header-align="center" align="center">
                    <template slot-scope="scope">
                        <el-tag
                            :class="{ 'yiji': (scope.row.grade === 1), 'erji': (scope.row.grade === 2), 'sanji': (scope.row.grade === 3) }">
                            {{ scope.row.grade === 1 ? '一级故障' : scope.row.grade === 2 ? '二级故障' : '三级故障' }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="stationSlide" label="站台侧" header-align="center" align="center">
                    <template slot-scope="scope">
                        <span v-if="scope.row.stationSlide === 'up'">上行</span>
                        <span v-if="scope.row.stationSlide === 'down'">下行</span>
                    </template>
                </el-table-column>
                <el-table-column prop="systemAb" label="A系/B系" header-align="center" align="center"></el-table-column>
                <el-table-column prop="deviceType" label="设备类型" header-align="center" align="center"></el-table-column>
                <el-table-column prop="createDate" label="发生时间" header-align="center" align="center" width="180"></el-table-column>
                <el-table-column prop="endDate" label="截止时间" header-align="center" align="center" width="180"></el-table-column>
                <el-table-column prop="detail" label="故障信息" header-align="center" align="center">
                    <template slot-scope="scope">
                        <span v-if="scope.row.deviceType === 'ASD滑动门'">
                            <div v-if="scope.row.stationSlide === 'up'">
                                <span>{{ scope.row.doorNo }} {{ scope.row.detail }}</span>
                            </div>
                            <div v-if="scope.row.stationSlide === 'down'">
                                <span>{{ scope.row.doorNo }} {{ scope.row.detail }}</span>
                            </div>
                        </span>
                        <span v-else>{{ scope.row.detail }}</span>
                    </template>
                </el-table-column>
            </el-table>
            <el-col :span="24" style="position:relative">
                <div class="export">
                    <!-- <el-checkbox v-model="checked" @change="toggleSelection(dataList)">全选</el-checkbox> -->
                    <span class="textColor" v-loading.fullscreen.lock="fullscreenLoading" @click="exportHandleNew()">批量导出</span>
                </div>
                <el-pagination background :current-page="page" :page-sizes="[10, 20, 50, 100]" :page-size="limit"
                    :total="total" layout="total, sizes, prev, pager, next, jumper" @size-change="pageSizeChangeHandle"
                    @current-change="pageCurrentChangeHandle">
                </el-pagination>
            </el-col>
        </el-row>
		<uploadTime ref="uploadTime" v-if="uploadTimeStatus"></uploadTime>
    </div>
</template>

<script>
import mixinViewModule from '@/mixins/view-module'
import utils from "@/utils/utils"
import printJS from 'print-js'
import qs from 'qs'
import { getOrder } from "@/utils";
import uploadTime from "@/components/uploadTime"
export default {
    mixins: [mixinViewModule],
	components:{
		  uploadTime
	},
    data() {
        this.columnChart = null;
        this.pieChart = null;
        return {
            mixinViewModuleOptions: {
                getDataListURL: '/psc/faillog/page',
                getDataListIsPage: true,
                activatedIsNeed: true,
                exportURL: '/psc/faillog/export'
                // deleteURL: '/sys/role',
                // deleteIsBatch: true
            },
            faultInfo: '一级故障',
            tableData: [],
            value1: '',
            value2: '',
            dataForm: {
                startTime: '',
                endTime: '',
                deviceType: '',
                grade: '',
                doorNo: '',
            },
            checked: false,
            options: utils.faultList,
            options1: [],
            doorNoList: [],
            month: [],//月份
            gzAll1: '',//故障一
            gzAll2: '',//故障二
            gzAll3: '',//故障三
            gzfirst: [],//一级故障
            gzSecond: [],//二级故障
            gzThird: [],//三级故障
            doorListup: [],//上行门数组
            doorListdown: [],//下行门数组
            pickerOptions0: {//结束时间不能大于开始时间
                disabledDate: (time) => {
                    if (this.dataForm.endTime) {
                        return time.getTime() > new Date(this.dataForm.endTime).getTime();
                    }
                }
            },
            pickerOptions1: {
                disabledDate: (time) => {
                    if (this.dataForm.startTime) {
                        return time.getTime() < new Date(this.dataForm.startTime).getTime() - 1 * 24 * 60 * 60 * 1000;//可以选择同一天
                    }
                }
            },
			uploadTimeStatus:false,
        }
    },
    activated() {
        this.init()
    },
    beforeDestroy() {
        this.columnChart.dispose();
        this.pieChart.dispose();
        this.columnChart = null;
        this.pieChart = null;
    },
    methods: {
        //开始时间显示
        startTimeChange() {
            let startTime = new Date(this.dataForm.startTime).getTime();
            let endTime = new Date(this.dataForm.endTime).getTime();
            if (endTime <= startTime && endTime !== '' && endTime !== 0 && startTime !== '' && startTime !== 0) {
                this.$message.error("开始时间不能大于结束时间")
                this.dataForm.startTime = ''
            }
        },
        //结束时间显示
        endTimeChange() {
            let startTime = new Date(this.dataForm.startTime).getTime();
            let endTime = new Date(this.dataForm.endTime).getTime();
            if (endTime <= startTime && startTime !== '' && startTime !== 0 && endTime !== '' && endTime !== 0) {
                this.$message.error("结束时间不能小于或等于开始时间")
                this.dataForm.endTime = ''
            }
        },
        init() {
            this.getdoorList();
            this.getDeviceList();
            this.getDoorNo();
            var p0 = new Promise((resolve, reject) => {
                this.getechartsData(() => {
                    resolve()
                })
            })
            Promise.all([p0]).then(() => {
                this.initEcharts1();
                this.initEcharts2();
            })
        },
        
        //获取单门的列表
        getdoorList() {
            this.doorListup = []
            this.doorListdown = []
            this.$http.get('/psc/door/getDoor').then(res => {
                res.data.data.up.forEach(item => {
                    if (item.doorType == 1) {
                        this.doorListup.push(item)
                    }
                })
                res.data.data.down.forEach(item => {
                    if (item.doorType == 1) {
                        this.doorListdown.push(item)
                    }
                })
				if(getOrder(res.data.data.up)==1){
					this.doorListup.reverse()
				}
				if(getOrder(res.data.data.down)==1){
					 this.doorListdown.reverse() //下行数据得倒叙
				}
            })

        },

        //获取设备列表
        getDeviceList(){
            this.$http.get('/psc/faillog/getDeviceType').then(res => {
                if (res.data.code == 0) {
                    this.options1 = res.data.data;
                }
            })
        },

        //获取日志中的门机编号
        getDoorNo(){
            this.$http.get('/psc/faillog/getDoorNo').then(res => {
                if (res.data.code == 0) {
                    this.doorNoList = res.data.data;
                }
            })
        },

        downBlob() {
            var params = qs.stringify({
                ...this.dataForm
            })
            this.$http.get(`/psc/faillog/export?${params}`,
                {
                    responseType: 'blob',
                }).then(res => {
                    // 获取文件名
                    let fileName = res.headers["content-disposition"]
                        .split(";")[1]
                        .split("filename=")[1];
                
                    // 文件名解码
                    fileName = decodeURI(fileName);
                    let url = window.URL.createObjectURL(new Blob([res.data], { type: 'arraybuffer' }))
                    const link = document.createElement('a')
                    link.style.display = 'none'
                    link.href = url
                    var mon = new Date().getMonth() + 1 < 10 ? '0' + (new Date().getMonth() + 1) : new Date().getMonth() + 1
                    var day = new Date().getDate() < 10 ? '0' + new Date().getDate() : new Date().getDate()
                    var time = new Date().getFullYear() + '' + mon + '' + day
                    link.setAttribute('download', fileName)
                    document.body.appendChild(link)
                    link.click()
                    document.body.removeChild(link)
                    //弹出弹框
                    this.$message({
                        message: '下载成功,文件在C:\Users\OIS\Downloads(c:\用户\OIS\下载)',
                        type: 'success',
                        duration: 3000,
                        onClose: () => {
                        }
                    })
                })
        },
        getData(callback) {
            var params = qs.stringify({
                ...this.dataForm
            })
            this.$http.get(`/psc/faillog/page?${params}`).then(res => {
                if (res.data.code == 0) {
                    this.dataList = res.data.data.list
                    this.total = res.data.data.total
                    callback()
                }
            })
        },
		exportHandleNew() {
			this.uploadTimeStatus = true
			this.$nextTick(() => {
				this.$refs.uploadTime.init(this.dataForm, this.mixinViewModuleOptions.exportURL)
			})
		},
        getechartsData(callback) {
            this.gzfirst = []
            this.gzSecond = []
            this.gzThird = []
            this.month = []
            this.$http.get('/psc/faillog/stat').then(res => {
                if (res.data.code == 0) {
                    this.gzAll1 = res.data.data.all.grade1
                    this.gzAll2 = res.data.data.all.grade2
                    this.gzAll3 = res.data.data.all.grade3
                    res.data.data.month.forEach(val => {
                        for (const key in val) {
                            this.month.push(key + '月')
                            this.gzfirst.push(val[key].grade1)
                            this.gzSecond.push(val[key].grade2)
                            this.gzThird.push(val[key].grade3)
                        }
                    })
                    // Object.keys(res.data.data.month).forEach(item=>{
                    // 	this.month.push(item+'月')
                    // })
                    // Object.values(res.data.data.month).forEach(item=>{
                    // 	this.gzfirst.push(item.grade1)
                    // 	this.gzSecond.push(item.grade2)
                    // 	this.gzThird.push(item.grade3)
                    // })
                    callback()
                }
            })
        },
        initEcharts1() {
            this.columnChart = this.$echarts.init(document.getElementById('chart1'))
            let option = {
                tooltip: {
                    trigger: "axis",
                    padding: [8, 10],
                    backgroundColor: '#fff',
                    axisPointer: {
                        type: "shadow",
                        textStyle: {
                            color: "#fff"
                        }
                    }
                },
                legend: {
                    data: ['一级', '二级', '三级'],
                    align: 'left',
                    right: 0,
                    textStyle: {
                        color: "#333",
                        fontSize: 12,
                        fontWeight: 200
                    },
                    itemWidth: 13,
                    itemHeight: 13,
                },
                grid: {
                    left: '0',
                    right: '0',
                    bottom: '8%',
                    top: '15%',
                    containLabel: true
                },
                label: {
                    show: true,
                    position: 'top',
                    color: '#333',
                    fontSize: 12,
                    // fontWeight: 700
                },
                xAxis: [{
                    type: 'category',
                    offset: 10,
                    data: this.month,
                    axisLabel: {
                        show: true,
                        color: "#333",
                        fontSize: 13,
                        fontWeight: 200
                    },
                }],
                yAxis: [{
                    type: 'value',
                    // name:"数量"

                }],
                series: [{
                    name: '一级',
                    type: 'bar',
                    data: this.gzfirst,
                    barWidth: 12, //柱子宽度
                    barGap: 0.5, //柱子之间间距
                    itemStyle: {
                        color: '#820000',
                        opacity: 1,
                    }
                }, {
                    name: '二级',
                    type: 'bar',
                    data: this.gzSecond,
                    barWidth: 12,
                    barGap: 0.5,
                    itemStyle: {
                        color: '#FF0000',
                        opacity: 1,
                    }
                }, {
                    name: '三级',
                    type: 'bar',
                    data: this.gzThird,
                    barWidth: 12,
                    barGap: 0.5,
                    itemStyle: {
                        color: '#FF8D1A',
                        opacity: 1,
                    }
                }]
            };
            this.columnChart.setOption(option);
            window.addEventListener("resize", () => {
                this.columnChart.resize()
            })
        },
        initEcharts2() {
            var that = this;
            this.pieChart = this.$echarts.init(document.getElementById('chart2'))
            const colorList = ['#820000', '#FF0000', '#FF8D1A']
            let option = {
                title: {
                    textStyle: {
                        fontSize: 16,
                        color: '#999',
                        lineHeight: 20
                    },
                    subtextStyle: {
                        fontSize: 28,
                        color: '#333'
                    },
                    textAlign: 'center',
                    left: '39.8%',
                    top: '45%'
                },
                tooltip: {
                    trigger: 'item',
                },
                legend: {
                    type: 'scroll',
                    orient: 'vertical',
                    right: '10%',
                    top: 'center',
                    itemGap: 15,
                    itemWidth: 16,
                    itemHeight: 16,
                    selectedMode: false,
                    data: ['一级故障', '二级故障', '三级故障'],
                    textStyle: {
                        color: '#77899c',
                        rich: {
                            uname: {
                                width: 50
                            },
                            unum: {
                                color: '#77899c',
                                width: 40,
                                align: 'left'
                            }
                        }
                    },
                    formatter(name) {
                        var sum = that.gzAll1 + that.gzAll2 + that.gzAll3
                        if (name == '一级故障') {
                            if (that.gzAll1 && that.gzAll1 !== 0) {
                                var bf1 = ((that.gzAll1 / sum) * 100).toFixed(2)
                                return `{uname|${name}}${bf1}%`
                            } else {
                                return `{uname|${name}}${0}%`
                            }

                        } else if (name == '二级故障') {
                            if (that.gzAll2 && that.gzAll2 !== 0) {
                                var bf1 = ((that.gzAll2 / sum) * 100).toFixed(2)
                                return `{uname|${name}}${bf1}%`
                            } else {
                                return `{uname|${name}}${0}%`
                            }

                        } else if (name == '三级故障') {
                            if (that.gzAll3 && that.gzAll3 !== 0) {
                                var bf1 = ((that.gzAll3 / sum) * 100).toFixed(2)
                                return `{uname|${name}}${bf1}%`
                            } else {
                                return `{uname|${name}}${0}%`
                            }
                        }

                    }
                },
                color: colorList,
                series: [
                    {
                        type: 'pie',
                        radius: [60, 90],
                        center: ['30%', '50%'],
                        label: {
                            show: false
                        },
                        labelLine: {
                            show: false
                        },
                        itemStyle: {
                            borderWidth: 3,
                            borderColor: '#fff'
                        },
                        data: [
                            { name: '一级故障', value: this.gzAll1 },
                            { name: '二级故障', value: this.gzAll2 },
                            { name: '三级故障', value: this.gzAll3 },

                        ],
                    }
                ]
            };
            this.pieChart.setOption(option);
            window.addEventListener("resize", () => {
                this.pieChart.resize()
            })
        },
        toggleSelection(rows) {
            if (rows) {
                rows.forEach(row => {
                    this.$refs.multipleTable.toggleRowSelection(row)
                })
            } else {
                this.$$refs.multipleTable.clearSelection()
            }
        },
        resetForm() {
            this.dataForm.startTime = ''
            this.dataForm.endTime = ''
            this.dataForm.deviceType = ''
            this.dataForm.grade = ''
            this.dataForm.doorNo = ''
            this.$http.get('/psc/faillog/page').then(res => {
                this.dataList = res.data.data.list
                this.total = res.data.data.total
            })
        },
        //打印表格
        printTable() {
            this.$http.get(`/psc/faillog/page?limit=${this.total}`).then(res => {
                let data = [];
                for (let i = 0; i < res.data.data.list.length; i++) {
                    data.push({
                        field1: i + 1,
                        field2: res.data.data.list[i].grade === 1 ? '一级故障' : res.data.data.list[i].grade === 2 ? '二级故障' : '三级故障',
                        field3: res.data.data.list[i].stationSlide === 'up' ? '上行' : '下行',
                        field4: res.data.data.list[i].deviceType,
                        field5: res.data.data.list[i].systemAb,
                        field6: res.data.data.list[i].createDate,
                        field7: res.data.data.list[i].endDate,
                        field8: res.data.data.list[i].detail,

                    })
                }
                printJS({
                    printable: data,
                    properties: [{
                        field: 'field1',
                        displayName: '序号',
                        columnSize: 1
                    }, {
                        field: 'field2',
                        displayName: '故障等级',
                        columnSize: 1
                    }, {
                        field: 'field3',
                        displayName: '站台侧',
                        columnSize: 1
                    }, {
                        field: 'field4',
                        displayName: '设备类型',
                        columnSize: 1
                    }, {
                        field: 'field5',
                        displayName: 'A系/B系',
                        columnSize: 1
                    }, {
                        field: 'field6',
                        displayName: '发生时间',
                        columnSize: 1
                    }, {
                        field: 'field7',
                        displayName: '截止时间',
                        columnSize: 1
                    }, {
                        field: 'field8',
                        displayName: '故障信息',
                        columnSize: 1
                    }],
                    type: 'json',
                    header: '故障记录',
                    //样式设置
                    gridStyle: 'border:2px solid #000000;text-align:center',
                    gridHeaderStyle: 'color:#000000; border:2px solid #000000;'
                })
            }).catch(function (error) { // 请求失败处理
                console.log(error);
            });
        },
        //合并导出
        downLoadAll() {
			this.uploadTimeStatus = true
			this.$nextTick(()=>{
				this.$refs.uploadTime.init(this.dataForm,'psc/faillog/mixexport')
			})
        }
    },
}
</script>

<style scoped> .el-form-item {
     margin-bottom: 1.8vh;
 }

 .bg-left {
     height: 39.8vh;
     min-height: 262px;
     margin-right: 0.52vw;
     padding: 1.5vh 1.1vw;
     background-color: #fff;
 }

 .queryText {
     display: inline-block;
     width: 67px;
     text-align: right;
     padding-right: 10px;
 }


 .bg-center {
     height: 39.8vh;
     min-height: 262px;
     margin-right: 0.52vw;
     padding: 1.3vh 0.7vw;
     background-color: #fff;
 }

 .chartTitleText {
     font-size: 14px;
 }

 .chartTitleText span {
     display: inline-block;
     width: 0.2vw;
     height: 0.37vh;
     margin: 0 0.3vw 0.27vh 0;
     background-color: #279EFB;
 }

 .chartBox {
     width: 100%;
     height: 100%;
 }


 .bg-right {
     height: 39.8vh;
     min-height: 262px;
     padding: 15px 15px;
     background-color: #fff;
 }


 .bg-bottom {
     /* height: 614px; */
     margin-top: 1.8vh;
     padding: 2.7vh 1.87vw 1.85vh 1vw;
     border-radius: 10px;
     background-color: #fff;
 }

 .titleContent {
     display: flex;
     position: relative;
     height: 3.7vh;
     margin-bottom: 1.5vh
 }

 .titleText {
     height: 3.7vh;
     line-height: 3.7vh;
     font-size: 16px;
     display: inline-block;
 }

 .print {
     position: absolute;
     right: 0;
     top: 1.1vh;
     cursor: pointer;
 }

 .print img {
     margin-right: 0.26vw;
 }

 .print span {
     font-size: 14px;
     color: #279EFB;
 }

 .export {
     position: absolute;
     top: 1.85vh;
     width: 11vw;
     height: 1.85vh;
     font-size: 14px;
 }

 .export .textColor {
     color: #279EFB;
     margin-left: 0.5vw;
     cursor: pointer;
 }

 .yiji {
     color: #fff;
     background-color: #820000;
     border: hidden;
 }

 .erji {
     color: #fff;
     background-color: #ff0000;
     border: hidden;
 }

 .sanji {
     color: #fff;
     background-color: #FF8D1A;
     border: hidden;
 }</style>